package io.gitee.sfch.chunmi.service.system.impl;

import io.gitee.sfch.chunmi.common.tool.PasswordTool;
import io.gitee.sfch.chunmi.controller.system.form.SystemLoginForm;
import io.gitee.sfch.chunmi.dao.system.entity.SystemUser;
import io.gitee.sfch.chunmi.service.system.LoginService;
import io.gitee.sfch.chunmi.service.system.SystemUserService;
import io.gitee.sfch.chunmi.service.system.exception.LoginErrorException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    private static final String SESSION_USER = "user";

    @Resource
    private SystemUserService systemUserService;

    @Override
    public void login(SystemLoginForm form, HttpServletRequest servletRequest) {
        // TODO 验证码校验
        SystemUser systemUser = systemUserService.findUser(form.getUsername());
        if (systemUser == null) {
            throw new LoginErrorException();
        }
        if (!PasswordTool.decryptEqual(form.getPassword(), systemUser.getPassword())) {
            throw new LoginErrorException();
        }
        HttpSession session = servletRequest.getSession();
        session.setAttribute(SESSION_USER, systemUser);
    }

    @Override
    public void logout(HttpServletRequest servletRequest) {
        HttpSession session = servletRequest.getSession();
        session.invalidate();
    }

    @Override
    public boolean alreadyLogin(HttpServletRequest servletRequest) {
        if (servletRequest.getCookies() == null) {
            return false;
        }
        HttpSession session = servletRequest.getSession();
        return session.getAttribute(SESSION_USER) != null;
    }

    @Override
    public SystemUser getSessionUser(HttpServletRequest servletRequest) {
        HttpSession session = servletRequest.getSession();
        return (SystemUser) session.getAttribute(SESSION_USER);
    }
}
